import _this from '../main'

// 设置localStorage
function setStorage (name, content) {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

// 获取localStorage
function getStorage (name) {
  if (!name) return
  return window.localStorage.getItem(name)
}

// 删除localStorage
function removeStorage (name) {
  if (!name) return
  window.localStorage.removeItem(name)
}

// 获取地址栏参数
function getUrl(name) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  let subIndex = window.location.href.indexOf('?') + 1
  let r = window.location.href.substr(subIndex).match(reg)
  if (r != null) {
    return decodeURI(r[2])
  } else {
    return null
  }
}

// 获取地址栏的token 存入缓存
function getUrlToken() {
  let token = getUrl('user_token')
  if (token) {
    setStorage('token', token)
  }
}

// 去登录
function toLogin() {
  _this.$router.push({
    path: '/login',
    query: {
      redirect: _this.$route.fullPath
    }
  })
}

// 判断是否在微信
function isWinxin() {
  let ua = window.navigator.userAgent.toLowerCase()
  if (ua.match(/MicroMessenger/i) && (ua.match(/MicroMessenger/i)[0] === 'micromessenger')) {
    return true
  } else {
    return false
  }
}

function getUrlPath(str) {
  const index = str.indexOf('#')
  str = str.substring(index + 1, str.length)
  return str
}

export default {
  setStorage: setStorage,
  getStorage: getStorage,
  removeStorage: removeStorage,
  getUrl: getUrl,
  getUrlToken: getUrlToken,
  toLogin: toLogin,
  isWinxin: isWinxin,
  getUrlPath: getUrlPath
}
